package com.szis.auth.oauth2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.szis.auth.oauth2.entity.Client;
import com.szis.auth.oauth2.mapper.ClientMapper;
import com.szis.auth.oauth2.request.ClientReq;
import com.szis.auth.oauth2.service.IClientService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szis.auth.runner.IdGenerator;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * oauth2客户端信息表 服务实现类
 * </p>
 *
 * @author yanxuelin
 * @since 2025-07-17
 */
@Service
public class ClientServiceImpl extends ServiceImpl<ClientMapper, Client> implements IClientService {

    @Resource
    private IdGenerator idGenerator;

    @Override
    public Client register(ClientReq req) {
        long count = baseMapper.selectCount(new LambdaQueryWrapper<Client>().eq(Client::getClientName, req.getClientName()));
        if(count != 0){
            throw new RuntimeException("客户端名称已存在");
        }
        Client client = new Client();
        BeanUtils.copyProperties(req, client);
        client.setBid(idGenerator.nextId());
        client.setClientSecret("123456");
        client.setScope(String.join(",", req.getScope()));
        client.setGrantType(String.join(",", req.getGrantType()));
        client.setRedirectUri(String.join(",", req.getRedirectUri()));
        client.setState(1);
        baseMapper.insert(client);
        return baseMapper.selectOne(new LambdaQueryWrapper<Client>().eq(Client::getBid, client.getBid()));
    }
}
